﻿using System;
using System.Collections;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using Gift.Model.ENUM;
using System.Text;
using Gift.DAL;
using Gift.Model;
using Gift.WebApp;
using Gift.Security;

namespace WebSite.admin.product
{
    public partial class openCard : BaseAdmin
    {

        DALCard theCard;
         
        tbCompany oCompany = new tbCompany();
        public string isDisplayGMS = "none";

        string sApplicatonCardID = string.Empty;

        private void BindProfessionAreaType()
        {
            DataSet dsType = new DataSet();
            DALProfessionAreaType theType = new DALProfessionAreaType();
            if (!string.IsNullOrEmpty(base.Administrator.CompanyId))
            {
                dsType = theType.GetListByCompanyId(base.Administrator.CompanyId);
            }
            else
            {
                dsType = theType.GetList(string.Empty);
            }
            if (dsType.Tables.Count > 0)
            {
                this.ddlProfessionAreaType.DataSource = dsType.Tables[0].DefaultView;
                this.ddlProfessionAreaType.DataTextField = "Name";
                this.ddlProfessionAreaType.DataValueField = "Id";
                this.ddlProfessionAreaType.DataBind();
            }
            this.ddlProfessionAreaType.Items.Insert(0, new ListItem("所属专区", ""));
        }


        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = this.ddlCurrentPage.SelectedIndex;
            this.GridViewBind("");
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if ((e.Row.RowType == DataControlRowType.Header) || (e.Row.RowType == DataControlRowType.DataRow))
            {
                CheckBox box = new CheckBox();
                box = (CheckBox)e.Row.FindControl("CheckBox1");
              
                if (box != null)
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                        LinkButton lbOpen = new LinkButton();
                        lbOpen = e.Row.FindControl("lbtnOpen") as LinkButton;

                        if (base.Administrator.AdminTypeId == "1")
                        {
                            lbOpen.Text = string.Empty;
                        }

                        else if(base.Administrator.CompanyId == null || (base.Administrator.CompanyId != null && base.Administrator.CompanyLevelId == 1))
                        {
                           
                            if (e.Row.Cells[7].Text == "申请激活中")
                            {
                                lbOpen.Text = "批准激活";
                            }
                            else
                            {
                                lbOpen.Visible = false;
                            }
                            isDisplayGMS = "block";

                            this.ibtnOpenCardCompany.Attributes["display"] = "none";
                        }
                    else  {

                          
                            lbOpen.Text = "申请激活";

                            if (e.Row.Cells[7].Text == "已领用未激活")
                            {
                                lbOpen.Visible = true;
                            }
                            else
                            {
                                lbOpen.Visible = false;
                            }
                        }
                        //当鼠标停留时更改背景色
                        e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#D7EDFD'");
                        //当鼠标移开时还原背景色
                        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                    }
                    else if (e.Row.RowType == DataControlRowType.Header)
                    {
                        box.Attributes.Add("onclick", "SelectAll(this.checked)");
                    }
                  
                }
            }
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            GridViewSortDirection = GridViewSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;

            string sqlsort = string.Empty;
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                sqlsort = " order by " + e.SortExpression + " ASC ";
            }
            else
            {
                sqlsort = sqlsort = " order by " + e.SortExpression + " DESC ";
            }
            this.GridViewBind(sqlsort);
        }

        public SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = SortDirection.Ascending;
                return (SortDirection)ViewState["sortDirection"];
            }
            set { ViewState["sortDirection"] = value; }
        }

        int RowCount
        {
            get
            {
                return int.Parse(this.ddlRowCount.SelectedItem.Value);
            }
        }

        private void GridViewBind(string Sqlsort)
        {
            string sStates = string.Empty;

            if (this.ddlStates.SelectedItem.Value != "")
            {
                if (this.ddlStates.SelectedItem.Value == "0")
                {
                    sStates = " and states in (0) ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),AddTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),AddTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                if (this.ddlStates.SelectedItem.Value == "1")
                {
                    sStates = " and states in (1,5) ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),opentime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),opentime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                else if (this.ddlStates.SelectedItem.Value == "2")
                {
                    sStates = " and states =2 ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),UsedTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),UsedTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                else if (this.ddlStates.SelectedItem.Value == "3")
                {
                    sStates = " and states =3 ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),DisableTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),DisableTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                else  if (this.ddlStates.SelectedItem.Value == "4")
                {
                    sStates = " and states =4 ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),AreadyPublishNoOpenTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),AreadyPublishNoOpenTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                else if (this.ddlStates.SelectedItem.Value == "6")
                {
                    sStates = " and states =6 ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),ApplicationOpenTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),ApplicationOpenTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
            }
         
            string sSort = "ORDER BY cardcode asc ";
            if (Sqlsort != string.Empty)
            {
                sSort = Sqlsort;
            }

            string sqlCount = " select count(1)  ";
            string sqlBefor = "select ROW_NUMBER() OVER (" + sSort + ") AS RowNumber,*,(select [name] from tbCardState where Id = ca.states) as statesName,convert(varchar(10),starttime,121) + ' 至 ' + convert(varchar(10),endtime,121) as exptime, (select Name from tbCardType where Id = ca.CardTypeId) as CardTypeName"
                        + " ,(select CompanyShortName from tbCompany where Id=ca.companyId  ) + '->' + isnull((select CompanyShortName from tbCompany where Id=ca.IICompanyId  ),' ') + '->' + isnull((select CompanyShortName from tbCompany where Id=ca.IIICompanyId  ),' ') + '->' + isnull((select CompanyShortName from tbCompany where Id=ca.IVCompanyId  ),' ') as companyName"
                         + ", case (select top 1 1 from tbGMS where cardid=ca.cardid) when 1 then '已发' else '未发' end as isSend ";


            StringBuilder sbSql = new StringBuilder();
            string sCompanyCode = GetCompanyCode();
            if (sCompanyCode == string.Empty)
            {
                this.GridView1.DataSource = new DataTable();
                this.GridView1.DataBind();
                return;
            }
            sbSql.AppendFormat(" from tbCard{0} ca where 1=1 ", sCompanyCode);
                     sbSql.Append(sStates);
            
            if(this.cardcodeFrom.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeFrom.Value.Trim());
                    sbSql.Append( " and convert(decimal,cardcode) >= " + this.cardcodeFrom.Value.Trim() + " ");
                }
                catch
                {
                   
                }
            }
            if (this.cardcodeTo.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeTo.Value.Trim());
                    sbSql.Append( " and convert(decimal,cardcode) <= " + this.cardcodeTo.Value.Trim() + " ");
                }
                catch
                {

                }
            }

            if (this.ddlAgentType.SelectedItem.Value == "0")
            {
                sbSql.AppendFormat(" and companyId in ({0}) ", base.Administrator.CompanyId);
            }
            else if (this.ddlAgentType.SelectedItem.Value == "1")
            {
                if (string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
                {
                    sbSql.AppendFormat(" and IICompanyId={0}  "
                                             , base.Administrator.CompanyId
                                             );
                }
                else
                {
                    sbSql.AppendFormat(" and IICompanyId={0} and IIICompanyId = {1} "
                                             , base.Administrator.CompanyId
                                             , this.ddlCompany0.SelectedItem.Value
                                             );
                }
            }
            else if (this.ddlAgentType.SelectedItem.Value == "2")
            {
                if (string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
                {
                    sbSql.AppendFormat(" and IIICompanyId={0}  "
                                             , base.Administrator.CompanyId
                                             );
                }
                else
                {
                    sbSql.AppendFormat(" and IIICompanyId={0} and IVCompanyId = {1} "
                                             , base.Administrator.CompanyId
                                             , this.ddlCompany0.SelectedItem.Value
                                             );
                }
            }
            else if (this.ddlAgentType.SelectedItem.Value == "3")
            {
                sbSql.AppendFormat(" and (IVCompanyId = {0}) "
                                      , base.Administrator.CompanyId
                                      );
            }
          
      
            if (this.ddlProfessionAreaType.SelectedItem.Value != "")
            {
                 sbSql.Append(" and CardTypeId in(select id from tbCardType where ProfessionAreaTypeId = " + this.ddlProfessionAreaType.SelectedItem.Value + ")");
            }
            if(!string.IsNullOrEmpty(this.ddlCardType.SelectedItem.Value))
            {
                 sbSql.Append(" and CardTypeId = " + this.ddlCardType.SelectedItem.Value);
            }

            sbSql.Append( " and publishWay='" + this.ddlPublishWay.SelectedItem.Value + "'");
            sqlCount = sqlCount + sbSql.ToString();
            string sql = sqlBefor + sbSql.ToString();
            DataTable dtRowCount = SQLAccess.GreatDs(sqlCount).Tables[0];
            int iRowCount = 0;
            int iPageCount = 0;
            if(dtRowCount.Rows.Count>0)
            {
                iRowCount = int.Parse(dtRowCount.Rows[0][0].ToString());
                if(iRowCount % RowCount ==0)
                {
                    iPageCount = iRowCount / RowCount;
                }else
                {
                    iPageCount = iRowCount / RowCount + 1;
                }
            }

            sql = string.Format(" SELECT TOP {2} * FROM ( {0} )a  WHERE RowNumber > {2} * ({1}) order by cardcode asc", sql, this.GridView1.PageIndex.ToString(), RowCount);      
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];

            this.LblCurrentIndex.Text = "当前第 " + ((this.GridView1.PageIndex + 1)).ToString() + "页";
            this.LblPageCount.Text = "共 " + iPageCount.ToString() + "页";
            this.LblRecordCount.Text = "总计 " + iRowCount.ToString() + "个记录";
            if (table.Rows.Count == 0)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = false;
                this.LblPageCount.Visible = false;
                this.LblRecordCount.Visible = false;
            }
            else if (iPageCount == 1)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = true;
                this.LblPageCount.Visible = true;
                this.LblRecordCount.Visible = true;
            } else{

                this.btnFirst.Visible = true;
                this.btnPrev.Visible = true;
                this.btnNext.Visible = true;
                this.btnLast.Visible = true;
                this.LblCurrentIndex.Visible = true;
                this.LblPageCount.Visible = true;
                this.LblRecordCount.Visible = true;
            }
            this.btnFirst.CommandName = "1";
            this.btnPrev.CommandName = (this.GridView1.PageIndex == 0) ? "1" : this.GridView1.PageIndex.ToString();
            this.btnNext.CommandName = (iPageCount == 1) ? iPageCount.ToString() : ((this.GridView1.PageIndex + 2)).ToString();
            this.btnLast.CommandName = iPageCount.ToString();
            this.ddlCurrentPage.Items.Clear();
            for (int i = 1; i <= iPageCount; i++)
            {
                this.ddlCurrentPage.Items.Add(i.ToString());
            }
            if (ddlCurrentPage.Items.Count > 0)
            {
                this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
            }


            if (Sqlsort == string.Empty)
            {
                table.DefaultView.Sort = "cardcode asc";
            }
            else
            {
                table.DefaultView.Sort = Sqlsort.Replace("order by", "");
            }
            this.GridView1.DataSource = table.DefaultView;
            this.GridView1.DataBind();

         //   this.SetCompanyMessage();
        }

        string GetCompanyCode()
        {
            string sCompanyCode = string.Empty;
            if (this.ddlAgentType.SelectedItem.Value == "0")
            {
                sCompanyCode = base.Administrator.CompanyCode;
            }
            else if (this.ddlAgentType.SelectedItem.Value == "1")
            {
                tbCompany tempIICompany = BaseFactory.theCompany.GetModel(int.Parse(base.Administrator.CompanyId));
                if (tempIICompany == null) return string.Empty;
                tbCompany tempCompany = BaseFactory.theCompany.GetModel(tempIICompany.ParentId);
                if (tempCompany == null) return string.Empty;
                sCompanyCode = tempCompany.CompanyCode;
            }
            else if (this.ddlAgentType.SelectedItem.Value == "2")
            {
                tbCompany tempIIICompany = BaseFactory.theCompany.GetModel(int.Parse(base.Administrator.CompanyId));
                if (tempIIICompany == null) return string.Empty;
                tbCompany tempIICompany = BaseFactory.theCompany.GetModel(tempIIICompany.ParentId);
                if (tempIICompany == null) return string.Empty;
                tbCompany tempCompany = BaseFactory.theCompany.GetModel(tempIICompany.ParentId);
                if (tempCompany == null) return string.Empty;
                sCompanyCode = tempCompany.CompanyCode;
            }
            else if (this.ddlAgentType.SelectedItem.Value == "3")
            {
                tbCompany tempIVCompany = BaseFactory.theCompany.GetModel(int.Parse(base.Administrator.CompanyId));
                if (tempIVCompany == null) return string.Empty;
                tbCompany tempIIICompany = BaseFactory.theCompany.GetModel(tempIVCompany.ParentId);
                if (tempIIICompany == null) return string.Empty;
                tbCompany tempIICompany = BaseFactory.theCompany.GetModel(tempIIICompany.ParentId);
                if (tempIICompany == null) return string.Empty;
                tbCompany tempCompany = BaseFactory.theCompany.GetModel(tempIICompany.ParentId);
                if (tempCompany == null) return string.Empty;
                sCompanyCode = tempCompany.CompanyCode;
            }
            if (theCard.IsExistTable(sCompanyCode))
            {
                return sCompanyCode;
            }
            else
            {
                return string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {      
            if (!base.IsPostBack)
            {
                if(theCard == null)
                {
                    theCard = new DALCard(base.Administrator.CompanyCode);
                }
      
                base.ValidateLoginRule(ERule.OpenCardManager);
                this.BindProvenctList();
                this.BindProfessionAreaType();
                this.BindCompanyLevel();
                this.BindCompanyList();
                this.BindCompanyListForDown();
                this.BindCardStates();
                this.BindCardType();
                this.GridViewBind("");
            }
        }

        void BindProvenctList()
        {
            DataSet ds = BaseFactory.theCompany.GetProvenceList(base.Administrator.CompanyId);
            this.ddlProvence.DataTextField = "provence";
            this.ddlProvence.DataValueField = "provence";
            this.ddlProvence.DataSource = ds;
            this.ddlProvence.DataBind();
            this.ddlProvence.Items.Insert(0, new ListItem("请选择省", ""));

            this.ddlProvence1.DataTextField = "provence";
            this.ddlProvence1.DataValueField = "provence";
            this.ddlProvence1.DataSource = ds;
            this.ddlProvence1.DataBind();
            this.ddlProvence1.Items.Insert(0, new ListItem("请选择省", ""));
        }

        void BindCompanyLevel()
        {
            DataSet ds = BaseFactory.theCompany.GetCompanyLevelList(base.Administrator.CompanyId);
            if (base.Administrator.CompanyId != null && base.Administrator.AdminTypeId != "1")
            {
                ds.Tables[0].DefaultView.RowFilter = " Id >= " + base.Administrator.CompanyLevelId;
            } 
            this.ddlLevel.DataTextField = "LevelName";
            this.ddlLevel.DataValueField = "Id";
            this.ddlLevel.DataSource = ds.Tables[0].DefaultView;
            this.ddlLevel.DataBind();
            this.ddlLevel.Items.Insert(0, new ListItem("请选择商家级别...", ""));

            this.ddlLevel1.DataTextField = "LevelName";
            this.ddlLevel1.DataValueField = "Id";
            this.ddlLevel1.DataSource = ds.Tables[0].DefaultView;
            this.ddlLevel1.DataBind();
            this.ddlLevel1.Items.Insert(0, new ListItem("请选择商家级别...", ""));
        }

        protected void PagerButtonClick(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = Convert.ToInt32(((LinkButton)sender).CommandName) - 1;
            this.GridViewBind("");
        }

        protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            this.GridViewBind("");

        }

        void SetCompanyMessage()
        {
            if (base.Administrator.CompanyId != null)
            {
                if (base.Administrator.CompanyLevelId != 1)
                {
                    decimal dCreditMoney = BaseFactory.theCompany.GetCompanyCreditMoney(base.Administrator.CompanyId);
                    this.tdOpenCardCompanyMessage.InnerText = string.Format("激活说明：您有预付款({0}元),授信额度（{1}元）,若您申请激活选中卡,如预付款充足,将直接激活选中的卡并扣除相应的预付款,如预付款不足,申请后的卡由上级商家审批激活。"
                        , BaseFactory.theCompany.GetCompanyMoney(base.Administrator.CompanyId) - dCreditMoney
                        , dCreditMoney);
                }
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "open")
            {
                int id = int.Parse(this.GridView1.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString());

                tbCardState oCardState;
                tbCard oCard;
                oCard = theCard.GetModel(id);
                oCardState = BaseFactory.theCardState.GetModel(oCard.states);
              
                if(base.Administrator.CompanyId == null || (base.Administrator.CompanyId != null && base.Administrator.CompanyLevelId == 1))
                {
                    SQLAccess.DoSql("update tbCard set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                 + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard.CompanyId order by AddDate desc),1)"
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard.IICompanyId order by AddDate desc),1)"
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard.IIICompanyId order by AddDate desc),1)"
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard.IVCompanyId order by AddDate desc),1)"
                                  + ",  updatetime='" + DateTime.Now.ToString()
                                 + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                                 + ";'  where cardid=" + id.ToString() + " and states = 6");
                    Response.Write("<script language=javascript>alert('修改成功！');</script>");
                    this.GridViewBind("");
                }else
                    if (base.Administrator.CompanyId != null)
                    {
                        sApplicatonCardID = id.ToString();
                        ibtnOpenCard_Click(null, null);
                    }
              
            }
        }

        protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
        {
            string sStates = "";
            string sql = "select cardcode as 卡号,cardprice as 金额,"
                        + " (select [Name] from tbCardType where id= CardTypeId) as 礼品卡类别,"
                        +" (select [Name] from tbCardState where Id = tbCard.States) as 状态,"
                         + " convert(varchar(10),starttime,121) as 专区开始日期, "
                        + " convert(varchar(10),endtime,121) as 专区截止日期,  publishWay as 发行方式,"
                        + " (select Name from tbCompany where Id=tbCard.companyId  ) + '->' + isnull((select Name from tbCompany where Id=tbCard.IICompanyId  ),' ') + '->' + isnull((select Name from tbCompany where Id=tbCard.IIICompanyId  ),' ') + '->' + isnull((select Name from tbCompany where Id=tbCard.IVCompanyId  ),' ') as 商家 "
                        + " from tbCard where 1=1 ";

            if (this.ddlStates.SelectedItem.Value != "")
            {
                if (this.ddlStates.SelectedItem.Value == "0")
                {
                    sStates = " and states in (0) ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),AddTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),AddTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                if (this.ddlStates.SelectedItem.Value == "1")
                {
                    sStates = " and states in (1,5) ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),opentime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),opentime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                else if (this.ddlStates.SelectedItem.Value == "2")
                {
                    sStates = " and states =2 ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),UsedTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),UsedTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                else if (this.ddlStates.SelectedItem.Value == "3")
                {
                    sStates = " and states =3 ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),DisableTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),DisableTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                else if (this.ddlStates.SelectedItem.Value == "4")
                {
                    sStates = " and states =4 ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),AreadyPublishNoOpenTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),AreadyPublishNoOpenTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
                else if (this.ddlStates.SelectedItem.Value == "6")
                {
                    sStates = " and states =6 ";
                    if (this.dateFrom.Value != "")
                    {
                        sStates = sStates + string.Format(" and   convert(varchar(10),ApplicationOpenTime,121) >= convert(varchar(10),'{0}',121) ", this.dateFrom.Value);
                    }
                    if (this.dateTo.Value != "")
                    {
                        sStates = sStates + string.Format(" and    convert(varchar(10),ApplicationOpenTime,121) <= convert(varchar(10),'{0}',121) ", this.dateTo.Value);
                    }
                }
            }
            sql = sql + sStates;

            if (this.cardcodeFrom.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeFrom.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) >= " + this.cardcodeFrom.Value.Trim() + " ";
                }
                catch
                {
                }
            }
            if (this.cardcodeTo.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeTo.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) <= " + this.cardcodeTo.Value.Trim() + " ";
                }
                catch
                {
                }
            }
            if (base.Administrator.AdminTypeId == "1" && string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
            {
                string sCompanyIds = GetCompanyListString();
                if (sCompanyIds != string.Empty)
                {
                    sql = sql + string.Format(" and (companyId in ({0}) or IICompanyId in ({0}) or IIICompanyId in ({0}) or IVCompanyId in ({0}))"
                                               , sCompanyIds);
                }
            }
            else  if (base.Administrator.CompanyId != null && string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
            {
                sql = sql + string.Format(" and (companyId={0} or IICompanyId={0} or IIICompanyId={0} or IVCompanyId={0})"
                                           , base.Administrator.CompanyId);
            }
            else if (this.ddlCompany0.SelectedItem.Value.Trim() != "")
            {
                sql = sql + string.Format(" and (companyId={0} or IICompanyId={0} or IIICompanyId={0} or IVCompanyId={0})"
                                           , this.ddlCompany0.SelectedItem.Value.Trim());
            }

            if (this.ddlProfessionAreaType.SelectedItem.Value != "")
            {
                sql = sql + " and CardTypeId in(select id from tbCardType where ProfessionAreaTypeId = " + this.ddlProfessionAreaType.SelectedItem.Value + ")";
            }

            sql = sql + " and publishWay='" + this.ddlPublishWay.SelectedItem.Value + "'";
            sql = sql + " order by cardcode desc";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];

            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";//设置导出文件的名称
            Gift.Utile.OperateExcel.ExportCSV(table, fileName);

        }

        string GetCompanyListString()
        {
            System.Text.StringBuilder sResult = new System.Text.StringBuilder();
            foreach (ListItem it in this.ddlCompany0.Items)
            {
                if (it.Value != string.Empty)
                {
                    sResult.Append(it.Value + ",");
                }
            }
            if (sResult.Length > 0)
            {
                return sResult.ToString().Substring(0, sResult.Length - 1);
            }
            return string.Empty;
        }

        private string BuildExportHTML(DataTable dt)
        {
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;
            int pagerecords = 100000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";
            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy-MM-dd") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }

        void BindCompanyList()
        {
      
                DataTable dt;
                StringBuilder sWhere = new System.Text.StringBuilder(" 1=1 ");
                if (this.ddlLevel.SelectedItem.Value != "")
                {
                    sWhere.Append(" and  LevelID = " + this.ddlLevel.SelectedItem.Value);
                }
                if (this.ddlProvence.SelectedItem.Value != "")
                {
                    sWhere.Append(" and  Provence = '" + this.ddlProvence.SelectedItem.Value + "'");
                }
                sWhere.AppendFormat(" and parentId ={0} ", base.Administrator.CompanyId);

                dt = BaseFactory.theCompany.GetList(sWhere.ToString()).Tables[0];
                this.ddlCompany0.DataTextField = "Name";
                this.ddlCompany0.DataValueField = "Id";
                this.ddlCompany0.DataSource = dt;
                this.ddlCompany0.DataBind();
                this.ddlCompany0.Items.Insert(0, new ListItem("请选择商家...", ""));
  

   
        }

        void BindCompanyListForDown()
        {
            DataTable dt;
            StringBuilder sWhere = new System.Text.StringBuilder(" 1=1 ");
            if (this.ddlLevel1.SelectedItem.Value != "")
            {
                sWhere.Append(" and  LevelID = " + this.ddlLevel1.SelectedItem.Value);
            }
            if (this.ddlProvence.SelectedItem.Value != "")
            {
                sWhere.Append(" and  Provence = '" + this.ddlProvence1.SelectedItem.Value + "'");
            }
            sWhere.AppendFormat(" and parentId ={0} ", base.Administrator.CompanyId);

            dt = BaseFactory.theCompany.GetList(sWhere.ToString()).Tables[0];

            this.ddlCompany1.DataTextField = "Name";
            this.ddlCompany1.DataValueField = "Id";
            this.ddlCompany1.DataSource = dt.DefaultView;
            this.ddlCompany1.DataBind();
            this.ddlCompany1.Items.Insert(0, new ListItem("请选择商家...", ""));

        }

        void BindCardStates()
        {
            DataSet dsCard = theCard.GetCardStateList();
            this.ddlStates.DataTextField = "Name";
            this.ddlStates.DataValueField = "Id";
            if (dsCard != null && dsCard.Tables.Count > 0)
            {
                dsCard.Tables[0].DefaultView.RowFilter = " id <> 5";
           
                this.ddlStates.DataSource = dsCard.Tables[0].DefaultView;
                this.ddlStates.DataBind();
                this.ddlStates.Items.Insert(0, new ListItem("请选择状态...", ""));
                if (!string.IsNullOrEmpty(Request.QueryString["states"]))
                {
                    ddlStates.Items.FindByValue(Request.QueryString["states"]).Selected = true;
                }
            }

            this.ddlStates1.DataTextField = "Name";
            this.ddlStates1.DataValueField = "Id";
            if (dsCard != null && dsCard.Tables.Count > 0)
            {
                if (base.Administrator.CompanyLevelId == 1)
                {
                    dsCard.Tables[0].DefaultView.RowFilter = " Id in(1,2,3) ";
                }
                this.ddlStates1.DataSource = dsCard.Tables[0].DefaultView;
                this.ddlStates1.DataBind();
            }
        }

        void BindCardType()
        {
            DataSet dsCardType = BaseFactory.theCardType.GetList("1=1");
            this.ddlCardType.DataTextField = "Name";
            this.ddlCardType.DataValueField = "Id";
            this.ddlCardType.DataSource = dsCardType;
            this.ddlCardType.DataBind();
            this.ddlCardType.Items.Insert(0, new ListItem("请选择...", ""));

        }

        protected void ibtnUpdateCompany_Click(object sender, ImageClickEventArgs e)
        {
        
            if (this.ddlCompany1.SelectedItem.Value != "")
            {
                string companyId = "";
                companyId = this.ddlCompany1.SelectedItem.Value;

                Hashtable htCardIds = new Hashtable();
                for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
                {
                    CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                    if (box.Checked)
                    {
                    htCardIds.Add(i.ToString(), this.GridView1.DataKeys[i].Value);
                    }
                }
            
                foreach (string key in  htCardIds.Keys)
                {

                    oCompany = BaseFactory.theCompany.GetModel(int.Parse(companyId));
                        string sUpdateBefor = string.Empty;
                        string sUpdateSql = string.Empty;

                        decimal companyOnSale = BaseFactory.theCompany.GetCompanyOnSale(companyId);

                       if (this.ddlAgentType.SelectedItem.Value == "0")
                       {
                           sUpdateSql = " IICompanyId = " + companyId + ", CompanyIIOnSale=" + companyOnSale;
                       }
                       else if (this.ddlAgentType.SelectedItem.Value == "1")
                       {

                           sUpdateSql = " IIICompanyId = " + companyId + ", CompanyIIIOnSale=" + companyOnSale;
                       }
                       else if (this.ddlAgentType.SelectedItem.Value == "2")
                       {

                           sUpdateSql = " IVCompanyId = " + companyId + ", CompanyIVOnSale=" + companyOnSale;
                       }

                       string sCompanyCode = GetCompanyCode();
                       if (sCompanyCode == string.Empty) return;
                       SQLAccess.DoSql("update tbCard" + sCompanyCode + " set " + sUpdateSql + ", states=4,AreadyPublishNoOpenTime='" + DateTime.Now.ToString() + "' where cardid=" + htCardIds[key] + " and states=0;"
                                       + " update tbCard" + sCompanyCode + " set " + sUpdateSql + ", remark = isnull(remark,'') +'" + base.Administrator.AdminUser + " 更新了公司为:" + oCompany.Name + ",时间:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";'   where cardid=" + htCardIds[key]);
                }
                this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"msg", "<script language=javascript>alert('批量更新商家成功！');</script>");
                this.GridViewBind("");
            }
        }

        protected void ibtnOpenCard_Click(object sender, ImageClickEventArgs e)
        {
            Hashtable htCardIds = new Hashtable();
            if (string.IsNullOrEmpty(sApplicatonCardID))
            {
                for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
                {
                    CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                    if (box.Checked)
                    {
                        htCardIds.Add(i.ToString(), this.GridView1.DataKeys[i].Value);
                    }
                }
            }
            else
            {
                htCardIds.Add(sApplicatonCardID, sApplicatonCardID);
                sApplicatonCardID = string.Empty;
            }
            string sCompanyCode = GetCompanyCode();
            if (sCompanyCode == string.Empty) return;

            foreach (string key in htCardIds.Keys)
            {
                    if (base.Administrator.CompanyId != null)
                    {
                        string sExeSql = string.Empty;
                        tbCompany oCompany = BaseFactory.theCompany.GetModel(int.Parse(base.Administrator.CompanyId));
                        decimal dCompanyMoney = BaseFactory.theCompany.GetCompanyMoney(base.Administrator.CompanyId);
                        decimal dOnSale = BaseFactory.theCompany.GetCompanyOnSale(base.Administrator.CompanyId);
                        decimal dCompanyMoneyDown = BaseFactory.theCompany.GetCompanyMoney(this.ddlCompany1.SelectedItem.Value);
                        decimal dOnSaleDown = BaseFactory.theCompany.GetCompanyOnSale(this.ddlCompany1.SelectedItem.Value);

                        if (this.ddlAgentType.SelectedItem.Value == "0")
                        {
                            tbCardState oCardState;
                            tbCard oCard;
                            oCard = theCard.GetModel(int.Parse(htCardIds[key].ToString()));
                            oCardState = BaseFactory.theCardState.GetModel(oCard.states);

                            sExeSql = " update tbCard" + sCompanyCode + " set states=6,ApplicationOpenTime='" + DateTime.Now.ToString()
                                    + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                                + ";' where  cardid=" + htCardIds[key] + " and  states !=1 and states !=2"
                                     + ";update tbCard" + sCompanyCode + " set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                + ", OpenAdminId = " + base.Administrator.AdminUserId
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard" + sCompanyCode + ".IICompanyId order by AddDate desc),1)"
                                 + ",  updatetime='" + DateTime.Now.ToString()
                                    + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                                 + "'  where cardprice * " + dOnSaleDown.ToString() + " <= " + dCompanyMoneyDown.ToString()
                                 + " and cardid=" + htCardIds[key] + " and states !=1 and states !=2";
                        }

                        else if (this.ddlAgentType.SelectedItem.Value == "1")
                        {
                            tbCardState oCardState;
                            tbCard oCard;
                            oCard = theCard.GetModel(int.Parse(htCardIds[key].ToString()));
                            oCardState = BaseFactory.theCardState.GetModel(oCard.states);

                            sExeSql = " update tbCard" + sCompanyCode + " set states=6,ApplicationOpenTime='" + DateTime.Now.ToString()
                                    + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                                + ";' where  cardid=" + htCardIds[key] + " and  states !=1 and states !=2"
                                     + ";update tbCard" + sCompanyCode + " set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                + ", OpenAdminId = " + base.Administrator.AdminUserId
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard" + sCompanyCode + ".IIICompanyId order by AddDate desc),1)"
                                 + ",  updatetime='" + DateTime.Now.ToString()
                                    + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                                 + "'  where cardprice * " + dOnSale.ToString() + " <= " + dCompanyMoney.ToString()
                                 + " and cardprice * " + dOnSaleDown.ToString() + " <= " + dCompanyMoneyDown.ToString()
                                 + " and cardid=" + htCardIds[key] + " and states !=1 and states !=2";
                        }

                        else if (this.ddlAgentType.SelectedItem.Value == "2")
                        {
                            decimal dCompanyMoneyUp = BaseFactory.theCompany.GetCompanyMoney(oCompany.ParentId.ToString());
                            tbCardState oCardState;
                            tbCard oCard;
                            oCard = theCard.GetModel(int.Parse(htCardIds[key].ToString()));
                            oCardState = BaseFactory.theCardState.GetModel(oCard.states);

                            sExeSql = " update tbCard" + sCompanyCode + " set states=6,ApplicationOpenTime='" + DateTime.Now.ToString()
                                    + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                                + ";' where  cardid=" + htCardIds[key] + " and  states !=1 and states !=2"
                                     + ";update tbCard" + sCompanyCode + " set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                + ", OpenAdminId = " + base.Administrator.AdminUserId
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard" + sCompanyCode + ".IVCompanyId order by AddDate desc),1)"
                                 + ",  updatetime='" + DateTime.Now.ToString()
                                    + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddHHmmss")
                                 + "'  where cardprice * CompanyIIOnSale <= " + dCompanyMoneyUp
                                 + " and cardprice * " + dOnSale.ToString() + " <= " + dCompanyMoney.ToString()
                                 + " and cardprice * " + dOnSaleDown.ToString() + " <= " + dCompanyMoneyDown.ToString()
                                 + " and cardid=" + htCardIds[key] + " and states !=1 and states !=2";
                        }

                        if (!string.IsNullOrEmpty(sExeSql))
                        {
                            SQLAccess.DoSql(sExeSql);
                        }

                }
            }
            Response.Write("<script language=javascript>alert('激活成功！');</script>");
            this.GridViewBind("");
        }

        protected void ibtnInport_Click(object sender, ImageClickEventArgs e)
        {
            if (this.FileUpload1.FileContent.Length <= 0)
            {
                Response.Write("<script>alert('请选择要导入的EXCEL文件！')</script>");
                return;
            }
            else
            {
                try
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
                    this.FileUpload1.SaveAs(Server.MapPath("../uploadTempFile/" + fileName));
                    DataTable dtResult = new DataTable();
                    dtResult = Gift.Utile.OperateExcel.InputCSV( Server.MapPath("../uploadTempFile/" + fileName));
                    DataRow[] dr = dtResult.Select();
                    int ss = dtResult.Rows.Count;
                    int rowsnum = dtResult.Rows.Count;
                    if (rowsnum == 0)
                    {
                        Response.Write("<script>alert('Excel表为空表,无数据！')</script>");
                        return;
                    }
                    int iInportSum = 0;
                    
                    for (int i = 0; i < rowsnum; i++)
                    {
                        string cardtypeId = "0";
                        tbCardType oCardType = BaseFactory.theCardType.GetModelByName(dr[i][3].ToString());
                        if (oCardType != null)
                        {
                             cardtypeId = oCardType.Id.ToString();
                        }
                       
                        string cardcode = dr[i][0].ToString();
                        string cardpass = dr[i][1].ToString();
                        string cardprice = dr[i][2].ToString()=="" ? "0" : dr[i][2].ToString();
                        string starttime = dr[i][4].ToString();
                        string endtime = dr[i][5].ToString();
                        string publishWay = dr[i][6].ToString();
                        string companyid = "0";
                        if (dr[i].ItemArray.Length > 6)
                        {
                            tbCompany oCompany = BaseFactory.theCompany.GetModelByName(dr[i][6].ToString());
                            if (oCompany != null)
                            {
                                companyid = oCompany.Id.ToString();
                            }
                        }
                        string sCompanyCode = GetCompanyCode();
                        if (sCompanyCode == string.Empty) return;

                        string sql = " if exists(select 1 from tbCard" + sCompanyCode + " where cardcode = '" + cardcode + "') "
                                    + " begin "
                                     + " update tbCard" + sCompanyCode + "  set cardtypeid = " + cardtypeId
                                     + " ,cardprice = " + cardprice
                                     + " ,starttime = '" + starttime + "'"
                                      + " ,endtime = '" + endtime + "'"
                                       + " ,lasttime = '" + endtime + "'"
                                     + " ,publishWay='" + publishWay + "'"
                                     + ", companyid = " + companyid
                                     + " where cardcode = '" + cardcode + "'"
                                     + " end"
                                     + " else"
                                     + " begin "
                                     + " insert into tbCard" + sCompanyCode + "(cardtypeId,cardcode,cardpas,cardprice,starttime,endtime,states,companyid,lasttime,publishWay)"
                                     + " values(" + cardtypeId + ",'" + cardcode + "','" + DESEncrypt.Encrypt(cardpass) + "'," + cardprice + ",'" + starttime + "','" + endtime + "',4," + companyid + ",'" + endtime + "','" + publishWay + "' )"
                                     + " end";
                                                 SQLAccess.DoSql(sql);
                            iInportSum++;
                     
                    }
                    Response.Write("<script>alert('成功导入" + iInportSum.ToString() + "条礼品卡记录！')</script>");
                    this.Dispose();
                    this.GridViewBind("");
                }
                catch (Exception ex)
                {
                    Response.Write("出错了：" + ex.ToString() );
                }
            }
        }

        protected void ibtnExport0_Click(object sender, ImageClickEventArgs e)
        {
            string sql = "select top 0 cardcode as 卡号,cardpas as 密码,cardprice as 金额,"
                      + " (select [Name] from tbCardType where id= CardTypeId) as 礼品卡类别,"
                       + " convert(varchar(10),starttime,121) as 专区开始日期,"
                      + " convert(varchar(10),endtime,121) as 专区截止日期,publishWay as 发行方式 ,'' as 商家 from tbCard where 1=1 ";
          

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];

            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";//设置导出文件的名称
            Gift.Utile.OperateExcel.ExportCSV(table, fileName);
        }

        protected void ibtnOpenCard0_Click(object sender, ImageClickEventArgs e)
        {
                tbCard oCard ;
          
             tbCardState oCardState;
             Hashtable htCardIds = new Hashtable();
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    htCardIds.Add(i.ToString(), this.GridView1.DataKeys[i].Value);
                }
            }

            foreach (string key in  htCardIds.Keys)
            {
                    oCard = theCard.GetModel(int.Parse(htCardIds[key].ToString()));
                    oCardState = BaseFactory.theCardState.GetModel(oCard.states);
                    if (this.ddlStates1.SelectedItem.Value == "1")
                    {
                        SQLAccess.DoSql("update tbCard set states=1,opentime='" + DateTime.Now.ToString() + "'," + "OpenAdminid=" + base.Administrator.AdminUserId
                                 + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard.CompanyId order by AddDate desc),1)"
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard.IICompanyId order by AddDate desc),1)"
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard.IIICompanyId order by AddDate desc),1)"
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = tbCard.IVCompanyId order by AddDate desc),1)"
                                 + ",  updatetime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name +"到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") +";'  where cardid=" + htCardIds[key] + " and states!=2 and  states!=1");
                    }
                    else
                    {
                        if (this.ddlStates1.SelectedItem.Value == "0")
                        {
                            SQLAccess.DoSql("update tbCard set states=" + this.ddlStates1.SelectedItem.Value + ",  opentime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                        }
                        else if (this.ddlStates1.SelectedItem.Value == "1")
                        {
                            SQLAccess.DoSql("update tbCard set states=" + this.ddlStates1.SelectedItem.Value + ",  opentime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                        }
                        else if (this.ddlStates1.SelectedItem.Value == "2")
                        {
                            SQLAccess.DoSql("update tbCard set states=" + this.ddlStates1.SelectedItem.Value + ",  UsedTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                        }
                        else if (this.ddlStates1.SelectedItem.Value == "3")
                        {
                            SQLAccess.DoSql("update tbCard set states=" + this.ddlStates1.SelectedItem.Value + ",  DisableTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                        }
                        else if (this.ddlStates1.SelectedItem.Value == "4")
                        {
                            SQLAccess.DoSql("update tbCard set states=" + this.ddlStates1.SelectedItem.Value + ",  AreadyPublishNoOpenTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                        }
                        else if (this.ddlStates1.SelectedItem.Value == "6")
                        {
                            SQLAccess.DoSql("update tbCard set states=" + this.ddlStates1.SelectedItem.Value + ",  ApplicationOpenTime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.Administrator.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddHHmmss") + ";' where cardid=" + htCardIds[key] + " and states!=2");
                        }
                }
            }
            Response.Write("<script language=javascript>alert('批量更新状态成功！');</script>");
            this.GridViewBind("");
        }


        protected void ibtnStoreOut_Click(object sender, ImageClickEventArgs e)
          {
              if (string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
              {
                  Response.Write("<script language=javascript>alert('请选取商家！');</script>");
                  return;
              }
              Response.Redirect("StoreOut.aspx?companyid=" + this.ddlCompany0.SelectedItem.Value + "&cardCodeFrom=" + this.cardcodeFrom.Value + "&cardCodeTo=" + this.cardcodeTo.Value);
 
          }

        protected void ddlLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompanyList();
        }

        protected void ddlProvence_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompanyList();
        }


        protected void ddlProvence1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompanyListForDown();
        }

        protected void ddlLevel1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompanyListForDown();
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ibtnReset_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("OpenCard.aspx");
        }

        protected void ddlAgentType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlAgentType.SelectedItem.Value == "3")
            {
                this.ddlProvence.Visible = false;
                this.tdLevelName.Visible = false;
                this.tdLevelValue.Visible = false;
                this.tdCompany.Visible = false;
                this.tdCompanySelect.Visible = false;
                this.ddlProvence1.Visible = false;
                this.ddlLevel1.Visible = false;
                this.ddlCompany1.Visible = false;
                this.ibtnUpdateCompany.Visible = false;
            }
            else
            {
                this.ddlProvence.Visible = true;
                this.tdLevelName.Visible = true;
                this.tdLevelValue.Visible = true;
                this.tdCompany.Visible = true;
                this.tdCompanySelect.Visible = true;
                this.ddlProvence1.Visible = true;
                this.ddlLevel1.Visible = true;
                this.ddlCompany1.Visible = true;
                this.ibtnUpdateCompany.Visible = true;
            }
            if (this.ddlAgentType.SelectedItem.Value != "1")
            {
                this.tdStates1.Visible = false;
                this.ddlStates1.Visible = false;
                this.ibtnOpenCard1.Visible = false;
                this.tdExport.Visible = false;
            }
            else
            {
                this.tdStates1.Visible = true;
                this.ddlStates1.Visible = true;
                this.ibtnOpenCard1.Visible = true;
                this.tdExport.Visible = true;
            }
        }





    }
}